export interface NginxFeature {
    id: string;
    name: string;
    description: string;
    category: string;
    template: string;
    highlights: HighlightRange[];
    documentation?: string;
}

export interface HighlightRange {
    start: number;
    end: number;
    type: 'important' | 'warning' | 'info' | 'success';
    description: string;
}

export const nginxFeatures: NginxFeature[] = [
    {
        id: 'streaming-response',
        name: '流式响应配置',
        description: '配置 Nginx 支持流式响应，适用于实时数据传输',
        category: '响应处理',
        template: `location /stream/ {
    # 启用流式响应
    proxy_buffering off;
    proxy_cache off;
    
    # 设置超时时间
    proxy_read_timeout 300s;
    proxy_connect_timeout 75s;
    proxy_send_timeout 300s;
    
    # 代理设置
    proxy_pass http://backend_server;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    
    # 禁用 gzip 压缩
    proxy_set_header Accept-Encoding "";
    
    # 设置响应头
    add_header Cache-Control "no-cache, no-store, must-revalidate";
    add_header Pragma "no-cache";
    add_header Expires "0";
}`,
        highlights: [
            { start: 2, end: 3, type: 'important', description: '禁用代理缓冲，确保实时传输' },
            { start: 4, end: 4, type: 'important', description: '禁用代理缓存' },
            { start: 6, end: 9, type: 'info', description: '设置较长的超时时间，避免连接中断' },
            { start: 11, end: 16, type: 'warning', description: '设置较长的超时时间，避免连接中断' },
            { start: 18, end: 19, type: 'info', description: '禁用 gzip 压缩，保持数据完整性' },
            { start: 21, end: 24, type: 'success', description: '设置响应头，确保不缓存' }
        ],
        documentation: '流式响应配置适用于需要实时数据传输的场景，如 WebSocket、Server-Sent Events 或大文件流式下载。'
    },
    {
        id: 'timeout-config',
        name: '超时配置优化',
        description: '优化各种超时设置，提高连接稳定性',
        category: '连接管理',
        template: `server {
    listen 80;
    server_name example.com;
    
    # 客户端超时配置
    client_header_timeout 60s;      # 客户端请求头超时
    client_body_timeout 60s;        # 客户端请求体超时
    send_timeout 60s;               # 发送响应超时
    
    # 长连接配置
    keepalive_timeout 65s;          # Keep-Alive 超时
    keepalive_requests 100;         # Keep-Alive 请求数
    
    # 上游服务器配置
    upstream backend {
        server 127.0.0.1:8080;
        keepalive 32;               # 连接池大小
    }
    
    location /api/ {
        # 代理超时配置
        proxy_connect_timeout 60s;      # 连接超时
        proxy_send_timeout 60s;         # 发送超时
        proxy_read_timeout 60s;         # 读取超时
        
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}`,
        highlights: [
            { start: 5, end: 8, type: 'important', description: '客户端相关超时设置' },
            { start: 10, end: 12, type: 'info', description: '长连接优化配置' },
            { start: 14, end: 18, type: 'warning', description: '上游服务器连接池配置' },
            { start: 21, end: 24, type: 'important', description: '代理超时配置（在location块内）' },
            { start: 26, end: 28, type: 'success', description: '启用 HTTP/1.1 长连接' }
        ],
        documentation: '合理的超时配置可以平衡性能和稳定性。客户端超时在server块，代理超时在location块内配置。'
    },
    {
        id: 'load-balancing',
        name: '负载均衡配置',
        description: '配置多种负载均衡策略和健康检查',
        category: '高可用',
        template: `# 加权轮询
upstream backend_servers {
    # 轮询策略（默认）
    server 192.168.1.10:8080 weight=3 max_fails=3 fail_timeout=30s;
    server 192.168.1.11:8080 weight=2 max_fails=3 fail_timeout=30s;
    server 192.168.1.12:8080 weight=1 max_fails=3 fail_timeout=30s backup;
    
    # 健康检查
    keepalive 32;
}

# 基于 IP 哈希的负载均衡
upstream ip_hash_backend {
    ip_hash;
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
    server 192.168.1.12:8080;
}

# 最少连接数负载均衡
upstream least_conn_backend {
    least_conn;
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
    server 192.168.1.12:8080;
}

server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_pass http://backend_servers;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        
        # 错误处理
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        proxy_next_upstream_tries 3;
        proxy_next_upstream_timeout 10s;
    }
}`,
        highlights: [
            { start: 1, end: 10, type: 'important', description: '加权轮询和故障转移配置' },
            { start: 12, end: 18, type: 'info', description: 'IP 哈希策略，确保会话一致性' },
            { start: 20, end: 26, type: 'info', description: '最少连接数策略' },
            { start: 33, end: 36, type: 'warning', description: '后端转发头' },
            { start: 38, end: 41, type: 'success', description: '上游故障转移配置' }
        ],
        documentation: '负载均衡配置可以提高系统的可用性和性能，支持多种策略和故障转移。'
    },
    {
        id: 'ssl-termination',
        name: 'SSL 终止配置',
        description: '配置 SSL/TLS 终止和证书管理',
        category: '安全',
        template: `# SSL 配置
server {
    listen 443 ssl http2;
    server_name example.com;
    
    # SSL 证书配置
    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    
    # SSL 协议和加密套件
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-CHACHA20-POLY1305;
    ssl_prefer_server_ciphers off;
    
    # SSL 会话配置
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;
    
    # 安全头配置
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    
    # HTTP/2 配置
    http2_push_preload on;
    
    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
    }
}

# HTTP 重定向到 HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}`,
        highlights: [
            { start: 3, end: 3, type: 'important', description: '启用 HTTP/2 支持' },
            { start: 6, end: 13, type: 'important', description: 'SSL 证书路径配置，现代 SSL 协议和加密套件' },
            { start: 15, end: 18, type: 'info', description: 'SSL 会话优化配置' },
            { start: 20, end: 24, type: 'success', description: '安全响应头配置' },
            { start: 38, end: 43, type: 'info', description: 'HTTP 到 HTTPS 重定向' }
        ],
        documentation: 'SSL 终止配置提供了安全的 HTTPS 访问，支持现代加密标准和安全头。'
    },
    {
        id: 'rate-limiting',
        name: '限流配置',
        description: '配置请求限流和 DDoS 防护',
        category: '安全',
        template: `# 限流区域定义
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
limit_req_zone $binary_remote_addr zone=download:10m rate=5r/s;

# 连接数限制
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

# API 限流
location /api/ {
    limit_req zone=api burst=20 nodelay;
    limit_conn conn_limit 10;
    
    proxy_pass http://backend;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    
    # 限流错误处理
    error_page 429 /429.html;
}

# 登录限流
location /login {
    limit_req zone=login burst=5 nodelay;
    
    proxy_pass http://backend;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

# 下载限流
location /download/ {
    limit_req zone=download burst=10 nodelay;
    limit_rate 1m;  # 限制下载速度
    
    proxy_pass http://backend;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

# 限流错误页面
location = /429.html {
    internal;
    return 429 '{"error": "Too Many Requests", "message": "Rate limit exceeded"}';
    add_header Content-Type application/json;
}`,
        highlights: [
            { start: 1, end: 4, type: 'important', description: '定义不同的限流区域和速率' },
            { start: 6, end: 7, type: 'warning', description: '连接数限制区域' },
            { start: 9, end: 20, type: 'important', description: 'API 限流配置' },
            { start: 22, end: 29, type: 'warning', description: '登录接口严格限流' },
            { start: 31, end: 39, type: 'info', description: '下载限流和速度限制' },
            { start: 41, end: 46, type: 'success', description: '自定义限流错误响应' }
        ],
        documentation: '限流配置可以有效防止 DDoS 攻击和资源滥用，保护服务器稳定性。'
    },
    {
        id: 'caching',
        name: '缓存配置',
        description: '配置静态资源缓存和代理缓存',
        category: '性能优化',
        template: `# 代理缓存配置
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;

# 缓存键配置
proxy_cache_key "$scheme$request_method$host$request_uri";

# 静态资源缓存
location ~* \\.(css|js|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    add_header Vary Accept-Encoding;
    
    # 启用 gzip 压缩
    gzip on;
    gzip_types text/css application/javascript image/svg+xml;
}

# API 缓存
location /api/cacheable/ {
    proxy_cache my_cache;
    proxy_cache_valid 200 302 10m;
    proxy_cache_valid 404 1m;
    proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
    proxy_cache_lock on;
    proxy_cache_lock_timeout 5s;
    
    proxy_pass http://backend;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    
    # 缓存控制头
    add_header X-Cache-Status $upstream_cache_status;
}

# 不缓存配置
location /api/dynamic/ {
    add_header Cache-Control "no-cache, no-store, must-revalidate";
    add_header Pragma "no-cache";
    add_header Expires "0";
    
    proxy_pass http://backend;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}`,
        highlights: [
            { start: 1, end: 2, type: 'important', description: '代理缓存路径和大小配置' },
            { start: 4, end: 5, type: 'info', description: '缓存键定义' },
            { start: 7, end: 16, type: 'success', description: '静态资源长期缓存配置' },
            { start: 18, end: 33, type: 'warning', description: 'API 缓存策略配置' },
            { start: 35, end: 44, type: 'important', description: '动态内容不缓存配置' }
        ],
        documentation: '合理的缓存配置可以显著提升网站性能，减少服务器负载和响应时间。'
    },
    {
        id: 'url-rewrite-redirect',
        name: 'URL 重写与重定向',
        description: '使用 rewrite 指令实现 URL 的重写或重定向',
        category: 'Web',
        template: `# URL 重写配置
location /old-path/ {
    # 内部重写（不改变浏览器地址）
    rewrite ^/old-path/(.*)$ /new-path/$1 last;
}

# 永久重定向 (301)
location /old-site/ {
    return 301 https://$host/new-site$request_uri;
}

# 临时重定向 (302)
location /temp-redirect/ {
    return 302 https://$host/temporary-path$request_uri;
}

# 条件重定向
location / {
    # 根据 User-Agent 重定向
    if ($http_user_agent ~* "Mobile") {
        return 301 https://$host/mobile$request_uri;
    }
    
    # 根据查询参数重定向
    if ($args ~* "utm_source=google") {
        return 301 https://$host/google$request_uri;
    }
    
    # 默认处理
    proxy_pass http://backend;
}

# 复杂重写规则
location /api/ {
    # 移除版本号
    rewrite ^/api/v1/(.*)$ /api/$1 last;
    
    # 添加默认版本
    rewrite ^/api/([^/]+)$ /api/v2/$1 last;
    
    # 处理特殊路径
    rewrite ^/api/users/([0-9]+)/profile$ /api/profiles/$1 last;
    
    proxy_pass http://backend;
}

# 文件扩展名处理
location ~* ^/(.+)\\.html$ {
    # 移除 .html 扩展名
    rewrite ^/(.+)\\.html$ /$1 permanent;
}

# 强制 HTTPS
if ($scheme != "https") {
    return 301 https://$server_name$request_uri;
}`,
        highlights: [
            { start: 1, end: 5, type: 'important', description: '内部重写，不改变浏览器地址栏' },
            { start: 7, end: 10, type: 'warning', description: '永久重定向，搜索引擎会更新索引' },
            { start: 12, end: 15, type: 'info', description: '临时重定向，搜索引擎不会更新索引' },
            { start: 17, end: 31, type: 'success', description: '条件重定向，根据各种条件进行重定向' },
            { start: 33, end: 45, type: 'important', description: '复杂重写规则，处理 API 路径' },
            { start: 47, end: 51, type: 'warning', description: '文件扩展名处理，SEO 友好' },
            { start: 53, end: 56, type: 'success', description: '强制 HTTPS 重定向' }
        ],
        documentation: 'URL 重写和重定向是网站维护和 SEO 优化的重要工具，支持内部重写和外部重定向。'
    },
    {
        id: 'access-control',
        name: '访问控制',
        description: '基于 IP 地址或其他条件限制访问',
        category: '安全',
        template: `# IP 地址访问控制
# 允许特定 IP 访问
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;

# 基于地理位置限制
geo $allowed_country {
    default 0;
    CN 1;  # 允许中国
    US 1;  # 允许美国
    JP 1;  # 允许日本
}

# 基于 User-Agent 限制
map $http_user_agent $bad_bot {
    default 0;
    ~* "bot|crawler|spider" 1;
    ~* "scraper|harvester" 1;
}

# 基于请求频率限制
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=1r/s;

# 管理后台访问控制
location /admin/ {
    # 只允许内网 IP
    allow 192.168.1.0/24;
    allow 10.0.0.0/8;
    deny all;
    
    # 基本认证
    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
    
    proxy_pass http://admin_backend;
}

# API 访问控制
location /api/ {
    # 检查地理位置
    if ($allowed_country = 0) {
        return 403;
    }
    
    # 检查恶意爬虫
    if ($bad_bot = 1) {
        return 403;
    }
    
    # 频率限制
    limit_req zone=api_limit burst=20 nodelay;
    
    proxy_pass http://api_backend;
}

# 登录接口访问控制
location /login {
    # 严格的频率限制
    limit_req zone=login_limit burst=5 nodelay;
    
    # 防止暴力破解
    limit_conn addr 1;
    
    proxy_pass http://auth_backend;
}

# 静态资源访问控制
location ~* \\.(php|asp|aspx|jsp)$ {
    # 禁止直接访问动态文件
    deny all;
    return 404;
}

# 基于时间限制访问
map $time_iso8601 $allowed_time {
    default 0;
    ~* "T(09|10|11|12|13|14|15|16|17|18):" 1;
}

location /business-hours/ {
    if ($allowed_time = 0) {
        return 503 "Service unavailable outside business hours";
    }
    
    proxy_pass http://business_backend;
}`,
        highlights: [
            { start: 1, end: 5, type: 'important', description: 'IP 地址白名单配置' },
            { start: 7, end: 13, type: 'warning', description: '基于地理位置限制访问' },
            { start: 15, end: 20, type: 'info', description: '恶意爬虫检测' },
            { start: 22, end: 24, type: 'success', description: '请求频率限制配置' },
            { start: 26, end: 38, type: 'important', description: '管理后台多重安全控制' },
            { start: 40, end: 56, type: 'warning', description: 'API 多层访问控制' },
            { start: 58, end: 67, type: 'success', description: '登录接口防暴力破解' },
            { start: 69, end: 74, type: 'important', description: '禁止直接访问动态文件' },
            { start: 76, end: 88, type: 'info', description: '基于时间的访问控制' }
        ],
        documentation: '访问控制是网站安全的重要组成部分，支持基于 IP、地理位置、时间、频率等多种条件的访问限制。'
    },
    {
        id: 'log-management',
        name: '日志管理',
        description: '配置访问日志和错误日志的位置及格式',
        category: '运维',
        template: `# 日志格式定义
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for"';

log_format detailed '$remote_addr - $remote_user [$time_local] "$request" '
                   '$status $body_bytes_sent "$http_referer" '
                   '"$http_user_agent" "$http_x_forwarded_for" '
                   'rt=$request_time uct="$upstream_connect_time" '
                   'uht="$upstream_header_time" urt="$upstream_response_time"';

log_format json escape=json '{'
    '"time_local":"$time_local",'
    '"remote_addr":"$remote_addr",'
    '"remote_user":"$remote_user",'
    '"request":"$request",'
    '"status": "$status",'
    '"body_bytes_sent":"$body_bytes_sent",'
    '"request_time":"$request_time",'
    '"http_referrer":"$http_referer",'
    '"http_user_agent":"$http_user_agent",'
    '"http_x_forwarded_for":"$http_x_forwarded_for",'
    '"upstream_addr":"$upstream_addr",'
    '"upstream_response_time":"$upstream_response_time"'
'}';

# 错误日志配置
error_log /var/log/nginx/error.log warn;
error_log /var/log/nginx/error_debug.log debug;

# 访问日志配置
access_log /var/log/nginx/access.log main;
access_log /var/log/nginx/access_json.log json;

# 特定路径的日志配置
location /api/ {
    # API 专用日志格式
    access_log /var/log/nginx/api_access.log detailed;
    access_log /var/log/nginx/api_access_json.log json;
    
    # 错误日志
    error_log /var/log/nginx/api_error.log;
    
    proxy_pass http://backend;
}

location /admin/ {
    # 管理后台日志
    access_log /var/log/nginx/admin_access.log detailed;
    access_log /var/log/nginx/admin_access_json.log json;
    
    # 记录所有管理操作
    error_log /var/log/nginx/admin_error.log info;
    
    proxy_pass http://admin_backend;
}

# 静态资源日志（可选）
location ~* \\.(css|js|png|jpg|jpeg|gif|ico|svg)$ {
    # 减少静态资源日志
    access_log off;
    # 或者使用简化的日志格式
    # access_log /var/log/nginx/static_access.log main;
}

# 健康检查日志
location /health {
    access_log off;
    error_log /var/log/nginx/health_error.log;
    
    return 200 "healthy";
}

# 日志轮转配置（在 nginx.conf 中）
# 使用 logrotate 进行日志轮转
# /var/log/nginx/*.log {
#     daily
#     missingok
#     rotate 52
#     compress
#     delaycompress
#     notifempty
#     create 644 nginx nginx
#     postrotate
#         /bin/kill -USR1 $(cat /var/run/nginx.pid)
#     endscript
# }

# 条件日志记录
map $status $loggable {
    ~^[23] 0;  # 不记录 2xx 和 3xx 状态码
    default 1; # 记录其他状态码
}

location / {
    access_log /var/log/nginx/access.log main if=$loggable;
    proxy_pass http://backend;
}`,
        highlights: [
            { start: 1, end: 4, type: 'important', description: '标准日志格式，包含基本访问信息' },
            { start: 6, end: 10, type: 'warning', description: '详细日志格式，包含响应时间信息' },
            { start: 12, end: 25, type: 'success', description: 'JSON 格式日志，便于日志分析' },
            { start: 27, end: 29, type: 'info', description: '错误日志配置，支持不同级别' },
            { start: 31, end: 33, type: 'important', description: '访问日志配置，支持多种格式' },
            { start: 35, end: 45, type: 'warning', description: 'API 专用日志配置' },
            { start: 47, end: 56, type: 'success', description: '管理后台日志配置' },
            { start: 58, end: 64, type: 'info', description: '静态资源日志优化' },
            { start: 66, end: 72, type: 'important', description: '健康检查日志配置' },
            { start: 89, end: 93, type: 'warning', description: '条件日志记录，减少日志量' }
        ],
        documentation: '完善的日志管理是运维和监控的基础，支持多种日志格式和条件记录，便于问题排查和性能分析。'
    },
    {
        id: 'websocket-support',
        name: 'WebSocket 支持',
        description: '配置 Nginx 支持 WebSocket 连接，实现实时双向通信',
        category: '响应处理',
        template: `# WebSocket 支持配置
location /ws/ {
    proxy_pass http://backend;
    
    # WebSocket 必需的头部设置
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    
    # 长连接超时设置
    proxy_read_timeout 86400s;
    proxy_send_timeout 86400s;
    
    # 禁用缓冲
    proxy_buffering off;
}`,
        highlights: [
            { start: 3, end: 3, type: 'warning', description: 'WebSocket 代理路径和后端地址' },
            { start: 5, end: 9, type: 'important', description: 'WebSocket 必需的 HTTP 头部设置' },
            { start: 11, end: 13, type: 'info', description: '长连接超时配置' },
            { start: 15, end: 16, type: 'success', description: '禁用缓冲，确保实时传输' }
        ],
        documentation: 'WebSocket 支持配置使 Nginx 能够代理 WebSocket 连接。只需配置必要的头部和超时设置即可。'
    }
];

// 按分类分组功能
export const featureCategories = [
    {
        name: '响应处理',
        features: nginxFeatures.filter(f => f.category === '响应处理')
    },
    {
        name: '连接管理',
        features: nginxFeatures.filter(f => f.category === '连接管理')
    },
    {
        name: '高可用',
        features: nginxFeatures.filter(f => f.category === '高可用')
    },
    {
        name: 'Web',
        features: nginxFeatures.filter(f => f.category === 'Web')
    },
    {
        name: '安全',
        features: nginxFeatures.filter(f => f.category === '安全')
    },
    {
        name: '性能优化',
        features: nginxFeatures.filter(f => f.category === '性能优化')
    },
    {
        name: '运维',
        features: nginxFeatures.filter(f => f.category === '运维')
    }
]; 